// node.js
const mume = require("@shd101wyy/mume");
const fs = require("fs");
const path = require('path')
const cheerio = require("cheerio");
const axios = require("axios");
const config = require('../config')
const log4js = require("log4js");
log4js.configure("log4js.json");

// es6
// import * as mume from "@shd101wyy/mume"


async function mdParse(src,targerPath) {
  // const logger = log4js.getLogger('dev');
  const logger = log4js.getLogger('markdown parse');

  
  // if file exist
  if(!fs.existsSync(src)){
    logger.error('Source file ['+ src +'] is not exist.');
    return;
  }
  
  if(path.extname(src).toLowerCase() !== '.md'){
    logger.error('Source file ['+ src +'] is not a markdown file.');
    return;
  }
  
  if(!fs.existsSync(targerPath)){
    logger.error('Target path ['+ targerPath +'] is not exist.');
    return;
  }

  const hasErr = false;
  const htmlFile = path.join(path.dirname(src) , path.basename(src, '.md') + '.html');  
  const contentFile = path.join(targerPath, path.basename(src, '.md') + '.html')

  await mume.init();

  // new Markdown engine
  const engine = new mume.MarkdownEngine({
    filePath: src,
    config: {
      previewTheme: "atom-dark.css",
      codeBlockTheme: "atom-dark.css",
      printBackground: true,
      enableScriptExecution: true, // <= for running code chunks
    },
  });

  // html export  
  logger.debug(`Export markdown file [${ src }] to html ......`);
  await engine.htmlExport({ 
    
    // 是否离线？ true:使用本地Css文件  false:使用外链
    offline: false, 
    runAllCodeChunks: false 
  })
  .catch(function (err){    
    logger.error(err);
    hasErr =true;
  });

  if(hasErr) return;

  // Load html file
  logger.debug(`Load html file [${htmlFile}] ......`);
  const myHtml = fs.readFileSync(htmlFile);
  const $ = cheerio.load(myHtml);

  const $bodyContent = $('body .markdown-preview');
  


  // get tags
  let tags;
  if($bodyContent.children().get(0).tagName !== 'h1'){
    logger.debug(`Get tags ......`);
    tags = $bodyContent.children().eq(0).text().trim().split(',');
    logger.debug(tags);

    // remove tags element
    $bodyContent.children().eq(0).remove();
  }


  // get title
  const title = $bodyContent.children().eq(0).text().trim();
  if (title === '') {
    logger.error(`Title is null.`);
    return;
  }
  logger.debug(`Get the article title:${title}`);
  
  // update image path
  $bodyContent.find('img').each((i, item)=>{
    const imgSrc = $(item).attr('src');
    $(item).attr('src','/' + imgSrc);
  });

  // save article body 
  logger.debug(`Save content html to target file [${contentFile}] ......`);
  fs.writeFileSync(contentFile, $bodyContent.eq(0).html(), function(err) {
    if (err) {
      hasErr =true;
      logger.error(err);
    }
  });

  if(hasErr) return;

  // remove title element
  $bodyContent.children().eq(0).remove();

  // Replace the line terminator with <br>, need save to DB
  const previewConrent = $bodyContent.text().trim().substr(0,200).replace(/$/mg," ");
  logger.debug(`Get the article preview content:${previewConrent}`);
  
  // save information to DB
  logger.debug(`Save information of the article to DB ......`);
  try {
    let articleExist = false;
    const filePath =  path.basename(src, '.md');

    //whether or not article is exist
    let resGet = await axios.get(config.apiServer.url + '/articles/path/' + encodeURIComponent(filePath));

    if (resGet.status === 200){
      logger.debug('resGet.data.code:' + resGet.data.code);
      if(resGet.data.code === 0){
        articleExist = true;
      } else if(resGet.data.code === 20201){
        articleExist = false;
      } else {
        logger.error(resGet.data);
      }     
    } else {
      logger.error('Get artice failed. error:' +  resGet.status);
    }

    let resSave;
    if(articleExist){
        // update 
        logger.debug(`update article [${filePath}]`)
        resSave = await axios.put(
        config.apiServer.url + '/article', 
        { 
          id:resGet.data.data.id,
          filePath: filePath, 
          title: title,
          preview: previewConrent,
          tags: tags,
        }
      )
    } else {
      // create  
      logger.debug(`create article [${filePath}]`);
      resSave = await axios.post(
        config.apiServer.url + '/article', 
        { 
          filePath: filePath, 
          title: title,
          preview: previewConrent,
          tags: tags,
        }
      )      
    }

    if(resSave.status === 200){
      if(resSave.data.code === 0 ){
        logger.info(`${filePath} save to DB successfully. It's ID is ${resSave.data.data.id}` ); 
      } else {
        logger.error(`${filePath} save to DB failed. Message:${JSON.stringify(resSave.data)}`);
      }
    } else {
      logger.error('Save article failed. error:' +  resCreate.status);
    }
  } catch (error) {
    logger.error(error);
  }
  

  // delete html file
  logger.debug(`Delete intermediate file [${ htmlFile }] ......`);
  fs.unlinkSync(htmlFile);

  return;
}
module.exports = mdParse;
//mdParse('G:/Document/hjklib/golang/Go语言有什么不同.md','G:/test');